<template>
  <div class="app-container">
    <!-- 操作按钮 -->
    <div class="toolbar">
      <div class="toolbar-left">
        <el-button type="primary" :icon="Plus" @click="handleAdd">
          新增设置
        </el-button>
      </div>
      <div class="toolbar-right">
        <el-button :icon="Refresh" @click="handleRefresh">刷新</el-button>
      </div>
    </div>

    <!-- 设置表格 -->
    <el-table v-loading="loading" :data="settingList" border stripe>
      <el-table-column label="金额区间" prop="amountRange" min-width="200" align="center">
        <template #default="{ row }">
          <span class="amount-range">
            ¥{{ formatAmount(row.minAmount) }} - ¥{{
              formatAmount(row.maxAmount)
            }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="收费金额" prop="feeAmount" min-width="120" align="center">
        <template #default="{ row }">
          <span class="fee-amount">
            {{
              `¥${formatAmount(row.feeAmount)}`
            }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="收费类型" prop="feeType" min-width="120" align="center">
        <template #default="{ row }">
          <el-tag :type="getFeeTypeTag(row.feeType)">
            {{ getFeeTypeText(row.feeType) }}
            <span style="display: inline-block;margin-left: 5px;" v-if="row.feeType === 'percentage'">
              {{ row.percentage }}%
            </span>
          </el-tag>

        </template>
      </el-table-column>
      <el-table-column label="状态" prop="status" width="100" align="center">
        <template #default="{ row }">
          <el-switch v-model="row.status" :active-value="1" :inactive-value="0" @change="handleStatusChange(row)" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createTime" width="180" align="center" />
      <el-table-column label="备注" prop="remark" min-width="150" show-overflow-tooltip />
      <el-table-column label="操作" width="200" align="center" fixed="right">
        <template #default="{ row }">
          <el-button type="warning" size="small" :icon="Edit" @click="handleEdit(row)">
            编辑
          </el-button>
          <el-button type="danger" size="small" :icon="Delete" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 设置表单对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px" @close="handleDialogClose">
      <el-form ref="settingFormRef" :model="settingForm" :rules="settingRules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="最小金额" prop="minAmount">
              <el-input-number v-model="settingForm.minAmount" :min="0" :precision="2" placeholder="请输入最小金额"
                style="width: 100%" @change="calculateFeeAmount" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最大金额" prop="maxAmount">
              <el-input-number v-model="settingForm.maxAmount" :min="0" :precision="2" placeholder="请输入最大金额"
                style="width: 100%" @change="calculateFeeAmount" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="收费类型" prop="feeType">
              <el-select v-model="settingForm.feeType" placeholder="请选择收费类型" style="width: 100%"
                @change="handleFeeTypeChange">
                <el-option label="固定费用" value="fixed" />
                <el-option label="按比例" value="percentage" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="settingForm.feeType === 'percentage'">
            <el-form-item label="收费比例" prop="percentage">
              <el-input-number v-model="settingForm.percentage" :min="0" :max="100" :precision="2" placeholder="请输入收费比例"
                style="width: 100%" @change="calculateFeeAmount">
                <template #append>%</template>
              </el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="收费金额" prop="feeAmount">
              <el-input-number v-model="settingForm.feeAmount" :min="0" :precision="2"
                :disabled="settingForm.feeType === 'percentage'" placeholder="请输入收费金额" style="width: 100%" />
              <div v-if="settingForm.feeType === 'percentage'" class="fee-tip">
                <el-text type="info" size="small">
                  按比例自动计算：{{ calculatedFeeText }}
                </el-text>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-form-item label="状态" prop="status">
          <el-radio-group v-model="settingForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item> -->
        <el-form-item label="备注" prop="remark">
          <el-input v-model="settingForm.remark" type="textarea" :rows="3" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Refresh, Plus, Delete, Edit } from "@element-plus/icons-vue";
import { getContractSetting, addContractSetting, updateContractSetting, delContractSetting, updateContractStatus } from "@/api/setting";

defineOptions({
  name: "ContractSetting",
});

// 响应式数据
const loading = ref(false);
const submitLoading = ref(false);
const dialogVisible = ref(false);
const isEdit = ref(false);
const total = ref(0);
const settingList = ref<SettingItem[]>([]);

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
});

// 设置表单
const settingForm = reactive({
  id: undefined,
  minAmount: 0,
  maxAmount: 0,
  feeAmount: 0,
  feeType: "fixed",
  percentage: 0,
  status: 0,
  remark: "",
});

// 表单验证规则
const settingRules: any = {
  minAmount: [
    { required: true, message: "请输入最小金额", trigger: "blur" },
    { type: "number", min: 0, message: "最小金额不能小于0", trigger: "blur" },
  ],
  maxAmount: [
    { required: true, message: "请输入最大金额", trigger: "blur" },
    { type: "number", min: 0, message: "最大金额不能小于0", trigger: "blur" },
    {
      validator: (rule: any, value: number, callback: Function) => {
        if (value <= settingForm.minAmount) {
          callback(new Error("最大金额必须大于最小金额"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  feeAmount: [
    { required: true, message: "请输入收费金额", trigger: "blur" },
    { type: "number", min: 0, message: "收费金额不能小于0", trigger: "blur" },
  ],
  feeType: [{ required: true, message: "请选择收费类型", trigger: "change" }],
  percentage: [
    {
      validator: (rule: any, value: number, callback: Function) => {
        if (settingForm.feeType === "percentage") {
          if (value === undefined || value === null || value <= 0) {
            callback(new Error("请输入有效的收费比例"));
          } else if (value > 100) {
            callback(new Error("收费比例不能超过100%"));
          } else {
            callback();
          }
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
};

// 计算属性
const dialogTitle = computed(() => (isEdit.value ? "编辑设置" : "新增设置"));

// 计算收费金额显示文本
const calculatedFeeText = computed(() => {
  if (settingForm.feeType === "percentage" && settingForm.percentage > 0) {
    const avgAmount = (settingForm.minAmount + settingForm.maxAmount) / 2;
    const calculatedFee = (avgAmount * settingForm.percentage) / 100;
    return `平均金额 ¥${formatAmount(avgAmount)} × ${settingForm.percentage}% = ¥${formatAmount(calculatedFee)}`;
  }
  return "请输入金额区间和比例";
});

// 引用
const settingFormRef = ref();

// 设置数据类型
interface SettingItem {
  id: number;
  minAmount: number;
  maxAmount: number;
  feeAmount: number;
  feeType: string;
  percentage?: number;
  status: number;
  createTime: string;
  remark?: string;
}

// 格式化金额
const formatAmount = (amount: number) => {
  return amount.toLocaleString("zh-CN", {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  });
};

// 获取收费类型标签颜色
const getFeeTypeTag: any = (type: string) => {
  const tagMap: Record<string, string> = {
    fixed: "primary",
    percentage: "success",
  };
  return tagMap[type] || "info";
};

// 获取收费类型文本
const getFeeTypeText = (type: string) => {
  const textMap: Record<string, string> = {
    fixed: "固定费用",
    percentage: "按比例",
  };
  return textMap[type] || "未知";
};

// 收费类型变化处理
const handleFeeTypeChange = () => {
  if (settingForm.feeType === "percentage") {
    settingForm.percentage = 0;
    calculateFeeAmount();
  } else {
    settingForm.feeAmount = 0;
  }
  // 清除收费金额字段的验证错误
  settingFormRef.value?.clearValidate("feeAmount");
};

// 计算收费金额
const calculateFeeAmount = () => {
  if (settingForm.feeType === "percentage" && settingForm.percentage > 0) {
    const avgAmount = (settingForm.minAmount + settingForm.maxAmount) / 2;
    settingForm.feeAmount = (avgAmount * settingForm.percentage) / 100;
  }
};

// 查询设置列表
const getSettingList = async () => {
  loading.value = true;
  try {
    // 模拟API调用
    let res = await getContractSetting();
    console.log(res);
    settingList.value = res.data
    total.value = res.data.length;
  } catch (error) {
    ElMessage.error("获取设置列表失败");
  } finally {
    loading.value = false;
  }
};

// 查询
const handleQuery = () => {
  getSettingList();
};

// 刷新
const handleRefresh = () => {
  getSettingList();
};

// 新增设置
const handleAdd = () => {
  isEdit.value = false;
  dialogVisible.value = true;
  resetSettingForm();
};

// 编辑设置
const handleEdit = (row: SettingItem) => {
  isEdit.value = true;
  dialogVisible.value = true;
  Object.assign(settingForm, {
    id: row.id,
    minAmount: Number(row.minAmount),
    maxAmount: Number(row.maxAmount),
    feeAmount: Number(row.feeAmount),
    feeType: row.feeType,
    percentage: Number(row.percentage || 0),
    status: row.status,
    remark: row.remark,
  });
};

// 删除设置
const handleDelete = async (row: SettingItem) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除金额区间 "¥${formatAmount(row.minAmount)} - ¥${formatAmount(row.maxAmount)}" 的设置吗？`,
      "删除确认",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );
    let res = await delContractSetting({ id: row.id });
    console.log(res, '..')
    if (res) {
      ElMessage.success("删除成功");
      getSettingList();
    }
  } catch (error) {
    // 用户取消删除
  }
};

// 状态切换
const handleStatusChange = async (row: SettingItem) => {
  try {
    let res = await updateContractStatus({ id: row.id, status: row.status });
    if (res) {
      ElMessage.success(`${row.status ? "启用" : "关闭"}成功`);
      getSettingList();
    }
  } catch (error) {
    // 恢复原状态
    row.status = row.status ? 0 : 1;
  }
};

// 提交表单
const handleSubmit = async () => {
  try {
    await settingFormRef.value?.validate();
    submitLoading.value = true;
    if (isEdit.value) {
      let res = await updateContractSetting(settingForm);
      if (res) {
        ElMessage.success(isEdit.value ? "更新成功" : "新增成功");
        dialogVisible.value = false;
        getSettingList();
      } else {
        ElMessage.error(res.msg);
      }
    } else {
      let res = await addContractSetting(settingForm);
      if (res) {
        ElMessage.success(isEdit.value ? "更新成功" : "新增成功");
        dialogVisible.value = false;
        getSettingList();
      } else {
        ElMessage.error(res.msg);
      }
    }
  } catch (error) {
    console.error("表单验证失败:", error);
  } finally {
    submitLoading.value = false;
  }
};

// 对话框关闭
const handleDialogClose = () => {
  settingFormRef.value?.resetFields();
  resetSettingForm();
};

// 重置设置表单
const resetSettingForm = () => {
  Object.assign(settingForm, {
    id: undefined,
    minAmount: 0,
    maxAmount: 0,
    feeAmount: 0,
    feeType: "fixed",
    percentage: 0,
    status: 0,
    remark: "",
  });
};

// 页面加载时获取数据
onMounted(() => {
  getSettingList();
});
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 24px;

  h2 {
    margin: 0 0 8px 0;
    color: #303133;
    font-size: 24px;
    font-weight: 600;
  }

  .page-description {
    margin: 0;
    color: #606266;
    font-size: 14px;
  }
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;

  .toolbar-left,
  .toolbar-right {
    display: flex;
    gap: 10px;
  }
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.dialog-footer {
  text-align: right;
}

.amount-range {
  font-weight: 600;
  color: #409eff;
}

.fee-amount {
  font-weight: 600;
  color: #67c23a;
}

.fee-tip {
  margin-top: 4px;

  .el-text {
    font-size: 12px;
  }
}

// 表格样式优化
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;

  .el-table__header {
    background-color: #f8f9fa;
  }
}

// 状态开关样式
:deep(.el-switch) {
  --el-switch-on-color: #13ce66;
  --el-switch-off-color: #ff4949;
}

// 标签样式
:deep(.el-tag) {
  border-radius: 12px;
}

// 输入框样式
:deep(.el-input-number) {
  .el-input__inner {
    text-align: left;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .toolbar {
    flex-direction: column;
    gap: 10px;

    .toolbar-left,
    .toolbar-right {
      width: 100%;
      justify-content: center;
    }
  }

  .page-header {
    text-align: center;

    h2 {
      font-size: 20px;
    }
  }
}
</style>
